<template>
  <div class="search-results">
    <div class="page-header">
      <h1 class="search-title">搜索结果: {{ keyword }}</h1>
      <el-button @click="$router.push('/')" type="primary" plain>
        <el-icon><ArrowLeft /></el-icon>
        返回首页
      </el-button>
    </div>

    <div class="products-container">
      <div class="products-grid">
        <div v-for="item in displayedProducts" :key="item.product.productId" class="product-card" @click="handleViewProduct(item)">
          <div class="product-image">
            <img :src="item.images?.[0]?.imageUrl || 'https://via.placeholder.com/200'" :alt="item.product.productName">
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ item.product.productName }}</h3>
            <p class="product-description">{{ item.product.productDescription }}</p>
            <div class="product-meta">
              <span class="product-price">¥{{ item.product.price }}</span>
              <span class="product-farm">{{ item.farm?.farmName || '未知农场' }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const keyword = ref('')
const productList = ref([])
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const displayedProducts = ref([])

// 加载搜索结果
const loadSearchResults = async () => {
  try {
    const response = await request({
      url: '/api/products/search',
      method: 'get',
      params: { keyword: keyword.value }
    })
    console.log('搜索结果:', response)
    productList.value = response || []
    total.value = productList.value.length
    updateDisplayedProducts()
    if (productList.value.length === 0) {
      ElMessage.info('未找到相关商品')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  }
}

// 更新显示的商品
const updateDisplayedProducts = () => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  displayedProducts.value = productList.value.slice(start, end)
}

// 处理分页
const handlePageChange = (page) => {
  currentPage.value = page
  updateDisplayedProducts()
}

// 查看商品详情
const handleViewProduct = (item) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/')
    return
  }
  router.push(`/product/${item.farm?.farmId}/${item.product.productId}`)
}

// 监听路由参数变化
watch(
  () => route.query.keyword,
  (newKeyword) => {
    if (newKeyword) {
      keyword.value = newKeyword
      loadSearchResults()
    }
  }
)

onMounted(() => {
  keyword.value = route.query.keyword || ''
  if (keyword.value) {
    loadSearchResults()
  }
})
</script>

<style scoped>
.search-results {
  padding: 40px;
  max-width: 1920px;
  margin: 0 auto;
  width: 90%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.search-title {
  font-size: 28px;
  color: #333;
  margin: 0;
}

.products-container {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30px;
  padding: 20px;
  margin-bottom: 20px;
}

.product-card {
  min-height: 320px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.product-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-description {
  font-size: 14px;
  color: #666;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
  flex: 1;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.product-price {
  font-size: 20px;
  font-weight: 600;
  color: #ff6b6b;
}

.product-farm {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 120px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-bottom: 20px;
}
</style> 